import {
  FrontUIActionProvider,
  IUILogicParams,
  IUIActionResult,
  IModalData,
  OpenAppViewCommand,
  SysUIActionTag,
} from '@ibiz-template/runtime';
import { IAppDEUIAction } from '@ibiz/model-core';
import { StringUtil, RuntimeModelError, ModelError } from '@ibiz-template/core';

/**
 * 人员新建行为适配器
 *
 * @export
 * @class PersonnelCreationUIActionProvider
 * @extends {FrontUIActionProvider}
 */
export class PersonnelCreationUIActionProvider extends FrontUIActionProvider {
  async execAction(
    action: IAppDEUIAction,
    args: IUILogicParams,
  ): Promise<IUIActionResult> {
    const { context, params, data, event, noWaitRoute, view } = args;
    let actionResult: IUIActionResult = {};
    // todo
    switch (action.frontProcessType) {
      case 'OPENHTMLPAGE': {
        const url = StringUtil.fill(action.htmlPageUrl!, context, data?.[0]);
        window.open(url, '_blank');
        break;
      }
      case 'TOP':
      case 'WIZARD': {
        const frontPSAppView = action.frontAppViewId;
        if (!frontPSAppView) {
          throw new RuntimeModelError(action, '未配置打开视图');
        }
        // 处理参数
        const { resultContext, resultParams } = await this.handleParams(
          action,
          context,
          data,
          params,
        );
        const res: IModalData | undefined = await ibiz.commands.execute(
          OpenAppViewCommand.TAG,
          frontPSAppView,
          resultContext,
          resultParams,
          { event, noWaitRoute },
        );
        // 打开视图取消操作
        if (!res?.ok) {
          actionResult.cancel = true;
        }

        if (res?.ok && res?.data) {
          actionResult.data = res.data;
          actionResult.nextContext = resultContext;
          actionResult.nextParams = { ...params, ...resultParams };
        }
        if (res?.ok) {
          view.call(SysUIActionTag.REFRESH);
        }

        break;
      }
      case 'OTHER':
        actionResult = this.doOther(action, args);
        break;
      default:
        throw new ModelError(
          action,
          `未支持的前台处理模式[${action.frontProcessType}]`,
        );
    }
    return actionResult;
  }
}
